<template>
  <div class="my-notes">
    <div class="note-list">
      <a-card
        v-for="note in notes"
        :key="note.id"
        class="note-card"
        @click="showModal(note)"
      >
        <template #title>
          <div class="note-title-center">
            <a @click.stop="goToVideo(note.outlineId)">{{ note.mediaFile.fileName.replace(/\.[^/.]+$/, '') }}</a>
          </div>
        </template>
        <div class="markdown-preview-short">
          <MarkdownRenderer :markdown="note.content" :jumpToTime="noop" />
        </div>
        <div style="margin-top: 8px;">
          <span>创建时间: {{ note.createTime }}</span>
        </div>
        <div class="note-delete-btn">
          <a-popconfirm title="确定要删除该笔记吗？" ok-text="是" cancel-text="否" @confirm.stop="deleteNote(note.id)">
            <a-button type="text" shape="circle" danger @click.stop>
              <template #icon>
                <DeleteOutlined />
              </template>
            </a-button>
          </a-popconfirm>
        </div>
      </a-card>
    </div>
    <!-- 全文模态框 -->
    <a-modal v-model:visible="modalVisible" width="60vw" :footer="null">
      <h2>{{ currentNoteTitle }}</h2>
      <MarkdownRenderer :markdown="currentNoteContent" :jumpToTime="noop" />
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { deleteDocById, getDocListByUserId } from '@/api/bizMediaDocController.ts'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getCourseBaseById, getOutlineById } from '@/api/bizCourseOutlinesController.ts'

const router = useRouter()
const loading = ref(false)

interface MediaFile {
  fileName: string
  videoId: number
  title?: string
}
interface NoteItem {
  id: number
  outlineId: number
  content: string
  createTime: string
  mediaFile: MediaFile
}
const notes = ref<NoteItem[]>([])
const modalVisible = ref(false)
const currentNoteTitle = ref('')
const currentNoteContent = ref('')

const noop = () => {}

const goToVideo = async (outlineId: number) => {
  console.log("++++++++", outlineId)
  const res = await getOutlineById({id: outlineId})
  if (res.data.code == 0) {
    const outline = res.data.data
    console.log(res.data)
    router.push(`/course/learn/${outline.courseId}/${outlineId}`)
  }
}

const getVideoTitle = (mediaFile: MediaFile) => {
  if (!mediaFile) return ''
  if (mediaFile.title) return mediaFile.title
  if (mediaFile.fileName) return mediaFile.fileName.replace(/\.[^/.]+$/, '')
  return ''
}

const showModal = (note: NoteItem) => {
  currentNoteTitle.value = getVideoTitle(note.mediaFile)
  currentNoteContent.value = note.content
  modalVisible.value = true
}

const isLong = (content: string) => {
  // 超过300字或10行就算长
  return content.length > 300 || content.split('\n').length > 10
}

const editNote = (id: number) => {
  router.push(`/note/${id}/edit`)
}

const deleteNote = async (id: number) => {
  const res = await deleteDocById({ id })
  if(res.data.code == 0) {
    message.success("删除笔记成功")
  } else {
    message.error('删除笔记失败')
  }
  fetchNotes()
}

const addNewNote = () => {
  router.push('/note/new')
}
const userInfo = ref<any>(null)

const checkUserLogin = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
}

const fetchNotes = async () => {
  try {
    loading.value = true
    const response = await getDocListByUserId({
      userId: userInfo.value.userId,
      current: 1,
      pageSize: 10,
      sortField: null,
      sortOrder: 'descend'
    } as any)
    // 打印返回数据
    console.log('----------', response.data)
    notes.value = (response.data.data || []).map((item: any) => ({
      id: item.id,
      content: item.content,
      createTime: item.createTime || item.create_time,
      outlineId: item.outlineId,
      mediaFile: {
        fileName: item.mediaFile?.fileName || '',
        videoId: item.mediaFile?.id || item.videoId || 0,
        title: item.mediaFile?.title || ''
      }
    }))
  } catch (error) {
    console.error('获取笔记失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  checkUserLogin()
  fetchNotes()
})
</script>

<style scoped>
.my-notes {
  padding: 24px;
}
.note-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}
.note-card {
  width: 350px;
  margin-bottom: 16px;
  transition: transform 0.25s cubic-bezier(.4,2,.6,1), box-shadow 0.25s cubic-bezier(.4,2,.6,1), z-index 0.25s;
  z-index: 1;
  cursor: pointer;
  position: relative;
}
.note-card:hover {
  transform: scale(1.01);
  box-shadow: 0 8px 32px rgba(0,0,0,0.18);
  z-index: 10;
}
.markdown-preview-short {
  max-height: 480px;
  overflow: hidden;
  position: relative;
}
.markdown-preview-short::after {
  content: '';
  position: absolute;
  left: 0; right: 0; bottom: 0;
  height: 32px;
  background: linear-gradient(to bottom, rgba(255,255,255,0), #fff 90%);
  pointer-events: none;
}
.note-title-center {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}
.note-delete-btn {
  position: absolute;
  right: 12px;
  bottom: 12px;
  z-index: 20;
}
</style>
